package model

import (
	"fmt"
	"server/global"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"

	"gorm.io/gorm"
)

type User struct {
	BaseModel
	UserID    string     `gorm:"size:32;not null;unique;comment:用户id"`
	Account   string     `gorm:"size:32;not null;unique;comment:账号"`
	IsAdmin   bool       `gorm:"default:false;comment:是否管理员"`
	Username  string     `gorm:"size:32;comment:用户名"`
	Nickname  string     `gorm:"size:32;comment:昵称"`
	Password  string     `gorm:"size:256;comment:密码"`
	Birthday  int64      `gorm:"index;comment:生日"`
	Avatar    string     `gorm:"avatar;comment:头像"`
	Mobile    string     `gorm:"size:16;comment:手机号"`
	Address   string     `gorm:"size:128;comment:地址"`
	Gender    int        `gorm:"default:1;comment:性别"`
	Email     string     `gorm:"size:64;comment:邮箱"`
	Ip        string     `gorm:"size:32;comment:ip"`
	Signature string     `gorm:"size:512;comment:签名"`
	Roles     []UserRole `gorm:"foreignKey:UserID;references:UserID;comment:用户角色关系"`
}

var (
	counter int64
	once    sync.Once
)

func initCounter() {
	var user User
	result := global.GA_DB.Order("created_at desc").Last(&user)
	if result.Error == nil {
		counter, _ = strconv.ParseInt(strings.Split(user.UserID, "uid")[1], 10, 64)
	}
}
func GenerateUserID() string {
	once.Do(initCounter)
	newCounter := atomic.AddInt64(&counter, 1)
	return fmt.Sprintf("uid%06d", newCounter)
}

func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
	if err := u.BaseModel.BeforeCreate(tx); err != nil {
		global.GA_LOGGER.Error(err.Error())
		return err
	}

	u.UserID = GenerateUserID()

	if u.Account == "admin" {
		if result := tx.Model(&u).Update("is_admin", true); result.Error != nil {
			global.GA_LOGGER.Error(result.Error.Error())
			return result.Error
		}
	}
	return
}
